
package lohmar.ashar.android.batterySaver;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.BatteryManager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;

import lohmar.ashar.android.batterySaver.helper.BluetoothHelper;
import lohmar.ashar.android.batterySaver.helper.GpsHelper;
import lohmar.ashar.android.batterySaver.helper.IServiceHelper;
import lohmar.ashar.android.batterySaver.helper.LightHelper;
import lohmar.ashar.android.batterySaver.helper.NetworkHelper;
import lohmar.ashar.android.batterySaver.helper.WifiHelper;
import lohmar.ashar.android.batterySaver.widget.BatteryView;

public class BatterySaverActivity extends Activity {
    /**
     * the name of the SharedPreferences
     */
    public static final String       PREFERENCES_NAME = "BS_PREFS";
    private static BroadcastReceiver bbr              = null;

    private int                      level            = -2;
    private int                      scale            = -2;

    private NetworkHelper            networkHelper    = null;
    private WifiHelper               wifiHelper       = null;
    private BluetoothHelper          bluetoothHelper;
    private GpsHelper                gpsHelper;
    private LightHelper              lightHelper;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        registerListener();
        initHelpers();
        setupButton((Button) findViewById(R.id.wifi), wifiHelper);
        setupButton((Button) findViewById(R.id.data), networkHelper);
        setupButton((Button) findViewById(R.id.blue), bluetoothHelper);
        setupButton((Button) findViewById(R.id.gps), gpsHelper);
        setupLightButton();
    }

    private void setupLightButton() {
        final AlertDialog alertDialog = getLightDialog();

        Button b = (Button) findViewById(R.id.bright);
        setupButtonColor(b, lightHelper.isBrightnessAutomatic());
        b.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                boolean newState = !lightHelper.isBrightnessAutomatic();
                lightHelper.setBrightnessAutomatic(newState);
                setupButtonColor((Button) v, newState);
            }
        });
        b.setOnLongClickListener(new OnLongClickListener() {

            @Override
            public boolean onLongClick(View v) {
                alertDialog.show();
                int p = lightHelper.getScreenBrighteness();
                SeekBar sb = (SeekBar) alertDialog.findViewById(R.id.lightProgress);
                sb.setProgress(p);
                return true;
            }
        });
    }

    private AlertDialog getLightDialog() {
        LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
        View layout = inflater.inflate(R.layout.light_dialog, (ViewGroup) findViewById(R.id.lightRoot));

        final TextView lbl = (TextView) layout.findViewById(R.id.lightVal);

        final SeekBar pb = (SeekBar) layout.findViewById(R.id.lightProgress);
        pb.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                lbl.setText("" + (progress + 10));
            }
        });
        AlertDialog.Builder builder = new Builder(this);
        builder.setTitle("Brigthness level");
        builder.setView(layout);
        builder.setCancelable(false).setPositiveButton("Ok", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int id) {
                Button b = (Button) findViewById(R.id.bright);
                setupButtonColor(b, false);
                lightHelper.setBrightnessAutomatic(false);
                lightHelper.setScreenBrighteness(pb.getProgress() + 10);
                dialog.cancel();
            }
        }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int id) {
                dialog.cancel();
            }
        });
        return builder.create();
    }

    protected void onBatteryChanged(Intent intent) {
        int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
        int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
        if (this.level != level || this.scale != scale) {
            this.level = level;
            this.scale = scale;
            BatteryView bv2 = (BatteryView) findViewById(R.id.batVal);
            bv2.setBatteryLevel((float) level / scale);
        }
    }

    @Override
    protected void onDestroy() {
        unregisterListener();
        super.onDestroy();
    }

    @Override
    protected void onPause() {
        unregisterListener();
        super.onPause();
    };

    @Override
    protected void onResume() {
        super.onResume();
        registerListener();
    }

    private void initHelpers() {
        networkHelper = new NetworkHelper(this);
        wifiHelper = new WifiHelper(this);
        bluetoothHelper = new BluetoothHelper(this);
        gpsHelper = new GpsHelper(this);
        lightHelper = new LightHelper(getContentResolver(), getWindow());
    }

    private void registerListener() {
        try {
            if (bbr == null) {
                bbr = new BroadcastReceiver() {

                    @Override
                    public void onReceive(Context context, Intent intent) {
                        if (intent.getAction().equals(Intent.ACTION_BATTERY_CHANGED)) {
                            onBatteryChanged(intent);
                        }
                    }
                };
                registerReceiver(bbr, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
            }
        } catch (Exception e) {
            e.printStackTrace();
            // TODO create a fucking logger that shows a message to the user and also logs to a file
        }
    }

    private void setupButtonColor(Button b, boolean enabled) {
        b.setTextColor(enabled ? Color.GREEN : Color.BLACK);
    }

    private void setupButton(Button b, final IServiceHelper serviceHelper) {
        if (serviceHelper == null) {
            throw new RuntimeException("Where the fuck is my helper ?");
        }
        if (serviceHelper.isServicePresent()) {
            b.setEnabled(true);
            setupButtonColor(b, serviceHelper.isServiceEnabled());
            b.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    boolean newServiceEnabled = !serviceHelper.isServiceEnabled();
                    serviceHelper.setServiceEnabled(newServiceEnabled);
                    setupButtonColor((Button) v, newServiceEnabled);
                }
            });
        } else {
            b.setEnabled(false);
        }

    }

    private void unregisterListener() {
        if (bbr != null) {
            unregisterReceiver(bbr);
            bbr = null;
        }
    }
}
